package cn.wolfcode.mq;

import ch.qos.logback.core.util.TimeUtil;
import cn.wolfcode.ws.WSServer;
import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
@RocketMQMessageListener(consumerGroup = "WsGroup",topic = MQConstants.ORDER_RESULT_TOPIC)
public class OrderResultQueueListener implements RocketMQListener<OrderMQResult> {
    @Override
    public void onMessage(OrderMQResult orderMQResult) {
            try {
                String token = orderMQResult.getToken();
                System.out.println("消费信息");
                int count = 3;
                while (count > 0){
                    Session session = WSServer.clients.get(token);
                    if (session != null) {
                        //如果能获取信息，返回数据给浏览器
                        session.getBasicRemote().sendText(JSON.toJSONString(orderMQResult));
                        return;
                    }
                    count--;
                    //说明WSServer.clients没有这个token对应的客户端，让他睡眠0.1s再去获取信息。
                    TimeUnit.MILLISECONDS.sleep(100);
                }
            } catch (Exception e) {
                e.printStackTrace();
        }
            //即使没有通知到客户端，用户也可以在订单页面中看到自己创建的订单信息。
    }
}
